# coding:utf-8
"""
Created on 2013-8-8

@author: Xen
"""
from common import tools

"""
生成api文档
"""


def api_docs(ctrl_map):
    urls = []
    apidoc_list = {}

    for ctrl_pkg in ctrl_map.keys():
        try:
            urls += __import__(ctrl_pkg).urls.urls
        except Exception as e:
            print(ctrl_pkg, e)
            continue

    for router in list(tools.group(urls, 2)):
        url = router[0]
        controller = router[1]
        dot = controller.rfind('.')
        module_name = controller[:dot]
        ctrl_name = controller[dot + 1:]
        control_class = tools.import_name(module_name, ctrl_name)
        doc = control_class.__doc__
        api = {
            'url': ctrl_map[controller[:controller.find('.')]] + url,
            'controller': controller,
            'doc': ''
        }
        if doc:
            docs = doc.split('\n')
            method = ''
            for d in docs:
                d = d.strip()
                if d.startswith('GET'):
                    method = 'get'
                    api['getargs'] = d[3:]
                    api['getdoc'] = ''
                elif d.startswith('POST'):
                    method = 'post'
                    api['postargs'] = d[4:]
                    api['postdoc'] = ''
                elif d.startswith('PUT'):
                    method = 'put'
                    api['putargs'] = d[3:]
                    api['putdoc'] = ''
                elif d.startswith('DELETE'):
                    method = 'delete'
                    api['deleteargs'] = d[6:]
                    api['deletedoc'] = ''
                elif d != '':
                    api[method + 'doc'] += d + '<br/>'

        if module_name in apidoc_list:
            apidoc_list[module_name].append(api)
        else:
            apidoc_list[module_name] = [api]

    return apidoc_list
